package com.trumeen.immichgallery.repository

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.trumeen.immichgallery.model.AppSettings
import com.trumeen.immichgallery.model.ImageSwitchPeriod
import com.trumeen.immichgallery.model.ImageType
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map

val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "immich_settings")

class SettingsDataStore(private val dataStore: DataStore<Preferences>) {

    private val SERVER_ADDRESS = stringPreferencesKey("server_address")
    private val USERNAME = stringPreferencesKey("username")
    private val PASSWORD = stringPreferencesKey("password")
    private val IMAGE_SWITCH_PERIOD = stringPreferencesKey("image_switch_period")
    private val IMAGE_TYPE = stringPreferencesKey("image_type")
    private val SELECTED_PERSON_ID = stringPreferencesKey("selected_person_id")

    val appSettingsFlow: Flow<AppSettings> = dataStore.data.map { preferences ->
        AppSettings(
            serverAddress = preferences[SERVER_ADDRESS] ?: "",
            username = preferences[USERNAME] ?: "",
            password = preferences[PASSWORD] ?: "",
            imageSwitchPeriod = runCatching {
                ImageSwitchPeriod.valueOf(preferences[IMAGE_SWITCH_PERIOD] ?: "")
            }.getOrElse { ImageSwitchPeriod.ONE_HOUR },
            imageType = runCatching {
                ImageType.valueOf(preferences[IMAGE_TYPE] ?: "")
            }.getOrElse { ImageType.LANDSCAPE },
            selectedPersonId = preferences[SELECTED_PERSON_ID] ?: ""
        )
    }

    suspend fun saveSelectedPersonId(id: String) {
        dataStore.edit { preferences ->
            preferences[SELECTED_PERSON_ID] = id
        }
    }

    suspend fun saveAppSettings(settings: AppSettings) {
        dataStore.edit { preferences ->
            preferences[SERVER_ADDRESS] = settings.serverAddress
            preferences[USERNAME] = settings.username
            preferences[PASSWORD] = settings.password
            preferences[IMAGE_SWITCH_PERIOD] = settings.imageSwitchPeriod.name
            preferences[IMAGE_TYPE] = settings.imageType.name
            preferences[SELECTED_PERSON_ID] = settings.selectedPersonId
        }
    }

    suspend fun updateServerAddress(address: String) {
        dataStore.edit { preferences ->
            preferences[SERVER_ADDRESS] = address
        }
    }

    suspend fun clearSettings() {
        dataStore.edit { it.clear() }
    }
}